package design.graduation.novelsystem.controller;

import design.graduation.novelsystem.model.domian.Role;
import design.graduation.novelsystem.model.dto.DataGridView;
import design.graduation.novelsystem.model.dto.ResultObj;
import design.graduation.novelsystem.model.vo.RoleVo;
import design.graduation.novelsystem.service.RoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: 洪少尉
 * @Date: 2020/4/15 03:20
 * @Description: 角色控制管理
 */
@RestController
@RequestMapping("role")
public class RoleController {
	@Autowired
	private RoleService roleService;
	/**
	 * 全查询
	 */
	@RequestMapping("loadAllRole")
	@RequiresPermissions("role:show")
	public Object loadAllRole(RoleVo roleVo){
		return this.roleService.queryAllRole(roleVo);
	}
	/**
	 * 查询所有可用角色
	 * 同时对选中管理者所拥有的角色进行反选
	 */
	@RequestMapping("loadAllAvailableRoleNoPage")
	public Object loadAllAvailableRoleNoPage(RoleVo roleVo){
		return this.roleService.queryAllAvailableRoleNoPage(roleVo);
	}

	/**
	 * 添加角色
	 */
	@RequiresPermissions("role:add")
	@PostMapping("addRole")
	public ResultObj addRole(Role role){
		if (this.roleService.saveRole(role)){
			return ResultObj.ADD_SUCCESS;
		}
		return ResultObj.ADD_ERROR;
	}

	/**
	 * 修改角色
	 */
	@PostMapping("updateRole")
	@RequiresPermissions("role:update")
	public ResultObj updateRole(Role role){
		if (this.roleService.updateRole(role)){
			return ResultObj.UPDATE_SUCCESS;
		}
		return ResultObj.UPDATE_ERROR;
	}


	/**
	 * 删除
	 */
	@PostMapping("deleteRole")
	@RequiresPermissions("role:delete")
	public ResultObj deleteRole(Integer id){
		if(this.roleService.removeById(id)){
			return ResultObj.DELETE_SUCCESS;
		}
			return ResultObj.DELETE_ERROR;
	}
	/**
	 * 批量删除
	 */
	@PostMapping("batchDeleteRole")
	@RequiresPermissions("role:delete")
	public ResultObj batchDeleteRole(Integer[] ids){
		if(null!=ids&&ids.length>0){
			List<Integer> idsList = new ArrayList<>(Arrays.asList(ids));
			if(this.roleService.removeByIds(idsList)){
				return ResultObj.DELETE_SUCCESS;
			}
			return ResultObj.DELETE_ERROR;
		}else{
			return ResultObj.DELETE_IDS_NULL;
		}
	}

	/**
	 * 根据角色ID查询角色拥有的菜单和权限ID
	 * @param id 角色ID
	 */
	@GetMapping("queryMenuIdsByRid")
	public Object queryMenuIdsByRid(Integer id){
		return new DataGridView(this.roleService.queryMenuIdsByRid(id));
	}
	/**
	 * 保存角色和菜单权限之间的关系
	 */
	@PostMapping("saveRoleMenu")
	public ResultObj saveRoleMenu(Integer rid, Integer[] mids){
		if (this.roleService.saveRoleMenu(rid,mids)){
			return ResultObj.DISPATCH_SUCCESS;
		}
		return ResultObj.DISPATCH_ERROR;
	}
}
